
import puppeteer from 'puppeteer';
import config from '../utils/constant.js'
import { getUrlParams } from '../utils/index.js';

// 获取四大类的洁面数据
export async function getCategoryData(key) {
  if (!key) return false
  let browser;
  try {
    const url = `${config.BASE_URL}/parts/${key}.html`
    browser = await puppeteer.launch({ headless: true, ignoreDefaultArgs: ['--enable-automation'] });
    const page = await browser.newPage();
    await page.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36");
    await page.setExtraHTTPHeaders({
      'Accept-Language': 'en-US,en;q=0.9',
      'sec-ch-ua': '"Not)A;Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"',
      'sec-ch-ua-mobile': '?0',
      'sec-ch-ua-platform': 'Windows'
    });
    await page.goto(url)
    await page.waitForSelector('#page2', {
      timeout: 20000
    })
    const res = await page.$('#page2')
    if (!res) {
      browser.close();
      return false
    }
    const r = await page.evaluate(() => {
      // 获取列表
      const list = document.querySelectorAll('#page2 > .diag-thumb');
      // 获取背景长图
      const imgElement = document.querySelector('.diag-thumb div a .ix');
      const style = window.getComputedStyle(imgElement);
      const backgroundImage = style.getPropertyValue('background-image');
      const url = backgroundImage.match(/url\(["']?(.+?)["']?\)/)[1];
      const getPositionY = (str) => {
        const match = str.match(/-?\d+px\s(-?\d+px)/);
        if (match) {
          const yValue = match[1];
          console.log('Y value:', yValue); // 输出 y 的值
          return yValue;
        } else {
          console.log('No match found.');
          return null;
        }
      }
      return {
        list: [...list].map(item => {
          const element = item.querySelector('.ix');
          const s = element.style;
          const width = s.width;
          const height = s.height;
          const backgroundPosition = s.backgroundPosition;
          return {
            // 原生js获取href属性
            href: item?.querySelector('a')?.getAttribute('href'),
            text: item?.querySelector('a')?.innerText,
            icon: {
              width,
              height,
              y: getPositionY(backgroundPosition)
            }
          }
        }),
        url: url ? url.replace('https://www.toyodiy.com', '/proxy') : ''
      }
    }, res);
    // 处理数据，将图片整理成base64返回到列表
    browser.close();
    if (r) {
      r.list.forEach(item => {
        item.href = getUrlParams(item.href)
      })
    }
    return r
  } catch (error) {
    console.log('getCategoryData: ', error)
    browser && browser.close();
    return false
  }
}

// 获取oe数据
export async function getOeData(key) {
  if (!key) return false
  const url = `${config.BASE_URL}/parts/${key}.html`
  let browser;
  try {
    browser = await puppeteer.launch({ headless: true, ignoreDefaultArgs: ['--enable-automation'] });
    const page = await browser.newPage();
    await page.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36");
    await page.setExtraHTTPHeaders({
      'Accept-Language': 'en-US,en;q=0.9',
      'sec-ch-ua': '"Not)A;Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"',
      'sec-ch-ua-mobile': '?0',
      'sec-ch-ua-platform': 'Windows'
    });
    await page.goto(url)
    // 界面page3渲染完毕
    await page.waitForSelector('#page3', {
      timeout: 20000
    })
    const res = await page.$('#t2')
    if (!res) {
      browser.close();
      return false
    }
    const r = await page.evaluate(() => {
      // do
      const list = document.querySelectorAll('#t2 > tbody');
      console.log(list)
      const s = [...list].map(item => {
        const [tr1, ...trs] = item.querySelectorAll('tr');
        return {
          oe: tr1.querySelector('td')?.innerText,
          desc: tr1.querySelector('td:nth-child(2)')?.innerText,
          children: [...trs].map(tr => {
            const [td1, td2, td3, td4] = tr.querySelectorAll('td');
            return {
              oe: td1?.innerText,
              desc: td2?.innerText,
              qty: td3?.innerText,
              price: td4?.innerText
            }
          })
        }
      })
      // 是否有下一页
      const pages = document.querySelectorAll('#page3 > div.phdr > a');
      const prev = Array.from(pages).find(el => el.innerText === '< Prev');
      const next = Array.from(pages).find(el => el.innerText === 'Next >');
      const url = document.querySelector('#i1')?.getAttribute('src')
      const getCurrentPage = (str) => {
        let match = str.match(/page (\d+) of (\d+)/);
        let page = match ? match[1] : null; // 第一页的数字
        let total = match ? match[2] : null; // 总页数的数字
        return {
          pageIndex: page,
          pagesize: total
        }
      }
      return {
        list: s,
        prev: prev ? prev.getAttribute('href') : null,
        next: next ? next.getAttribute('href') : null,
        ...getCurrentPage(document.querySelector('#trmore')?.innerText || '0 of 0'),
        background: url ? `/proxy/parts/${url}` : ''
      }
    }, res);
    // 地址转换
    if (r) {
      if (r.prev) {
        r.prev = getUrlParams(r.prev)
      }
      if (r.next) {
        r.next = getUrlParams(r.next)
      }
    }
    browser.close();
    return r
  } catch (error) {
    console.log('getOeData: ', error)
    browser && browser.close();
    return false
  }
}